QualPlot <- function(M,sampleColours = "gray",components = c(1,2)){
require(affy) #plotDensity
tempCols <- sampleColours

if(length(sampleColours) ==1){
 sampleColours <- colnames(M)
 sampleColours[] <- tempCols
} 

pcaModel <- prcomp(t(M))
E <- rowSums((pcaModel$x[,components*-1])^2)
H <- rowSums((pcaModel$x[,components])^2)
#Scores plot
x11()
plot(pcaModel)
X11()
### par(bg="white", cex.main=0.75)
split.screen(figs=c(2,2), erase=TRUE)


screen(n=1)
plot(pcaModel$x[,components[1]],pcaModel$x[,components[2]],xlab=paste("component ",as.character(components[1])),main = "Samples",ylab=paste("component ",as.character(components[2])),pch = 19,col = sampleColours)
abline(h = 0,v = 0)
scores.plot <- dev.cur()
abline(h = 0,v = 0)

#Sets map plot
screen(n = 2)
#Density
denPlot <- plotDensity(M, col="gray")

#Sets map plot
screen(n = 3)
#Influence plot
plot(H,E,xlab="leverage",main = "Influence",ylab="residual",pch = 19,col = sampleColours)

#box plot
screen(n = 4)
boxplot(data.frame((M)),main="Boxplot",range= 2,pch = 20,names =NULL,col = sampleColours)

#Array plot



new.cycle = TRUE

while (new.cycle == TRUE){
 type <-  menu(c("scores", "influence"),title = "Select mapping",graphics = FALSE)
 type <- c("scores","influence")[type]
 
 
 if (type == "scores"){
  screen(n = 1,new = F)
  ind <- identify(pcaModel$x[,components[1]],pcaModel$x[,components[2]],n = 1)
  screen(n = 2)
  plotDensity(M,col = "gray",main = colnames(M)[ind])
  points(x = denPlot$all.x[,ind],y = denPlot$all.y[,ind],col = "purple",type = "l")

  screen(n = 4)
  tempCols <- sampleColours
  tempCols[ind] <- "purple"
  boxplot(data.frame((M)),main="Boxplot",range= 2,pch = 20,names =NULL,col = tempCols)
 
  screen(n = 3)
  #Influence plot
  plot(H,E,xlab="leverage",main = "Influence",ylab="residual",pch = 19,col = tempCols)
  
 }
 
 if (type == "influence"){
  screen(n = 3,new = F)
  ind <- identify(H,E,n = 1)
  screen(n = 2)
  plotDensity(M,col = "gray",main = colnames(M)[ind])
  points(x = denPlot$all.x[,ind],y = denPlot$all.y[,ind],col = "red",type = "l")  
  screen(n = 4)
  tempCols <- sampleColours
  tempCols[ind] <- "purple"
  boxplot(data.frame((M)),main="Boxplot",range= 2,pch = 20,names =NULL,col = tempCols)

  screen(n=1)
  plot(pcaModel$x[,components[1]],pcaModel$x[,components[2]],xlab=paste("component ",as.character(components[1])),main = "Samples",ylab=paste("component ",as.character(components[2])),pch = 19,col = tempCols)
  abline(h = 0,v = 0)
  scores.plot <- dev.cur()
  abline(h = 0,v = 0)

 }

 if(type == "multi select"){
  screen(n = 1,new = F)
  loc <- locator(n = 9,type = "l")
  pip <- point.in.polygon(point.x = PLSmodel$W[,components[1]], point.y = PLSmodel$W[,components[2]], pol.x = loc$x, pol.y = loc$y)   
 
 }

  
} 
} 
 
